<template>
  <a-modal v-model:visible="modalVisible" :title="headerTitle" width="90%" :footer="null" @cancel="cancle">
    <a-form ref="modalRef" :rules="rules" :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="内容标题" name="title">
        <a-input placeholder="请输入内容标题" v-model:value="modalForm.title" :disabled="disabled"></a-input>
      </a-form-item>
      <a-form-item label="所属内容分类" name="address">
        <a-select
          ref="select"
          v-model:value="modalForm.address"
          style="width: 120px"
          @focus="focus"
          @change="handleChange"
          placeholder="请选择内容分类"
          :disabled="disabled"
        >
          <a-select-option :value="item.name" v-for="item in contentCategory" :key="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="内容" name="tinymceValue">
        <Tinymce ref="editor" :value="modalForm.tinymceValue" :disabled="disabled" @input="tinymceInput">></Tinymce>
      </a-form-item>
      <a-form-item label="添加缩略图" name="img">
        <a-row style="">
          <a-col :span="4" :offset="1">
            <a-upload
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              list-type="picture-card"
              v-model:file-list="fileList"
              :multiple="true"
              @preview="handlePreview"
              :before-upload="beforeUpload"
              @change="handleChange1"
            >
              <a-button type="primary">本地上传</a-button>
            </a-upload>
          </a-col>
          <!-- align-self:flex-end;-->
          <!-- <a-col :span="4" :offset="2" style="align-self:flex-end;margin-bottom:16px;" >
            <a-button type="primary">图库上传</a-button>
          </a-col> -->
        </a-row>
      </a-form-item>
      <a-form-item label="状态" name="modafstatus">
        <a-radio-group name="radioGroup" v-model:value="modalForm.status">
          <a-radio value="0" :disabled="disabled">显示</a-radio>
          <a-radio value="1" :disabled="disabled">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <!-- 确定和取消 -->
    <a-row>
      <a-col :span="4" :offset="8" v-if="!disabled">
        <a-button type="primary" size="large" @click="save">保存</a-button>
      </a-col>
      <a-col :span="8" :offset="disabled ? '12' : '0'">
        <a-button size="large" @click="cancle">{{ diabled ? '关闭' : '取消' }}</a-button>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import { Modal, message } from 'ant-design-vue'
import { ref, h, reactive, onMounted, computed, watch, watchEffect } from 'vue'
import Tinymce from '@/components/common/tinymce/tinymce'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
export default {
  // props中是不可改变的参数
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    Tinymce,
    PlusOutlined,
    LoadingOutlined
  },
  setup(props, { emit, attrs }) {
    const headerTitle = ref('新增内容')
    const modalRef = ref('')
    const modalForm = reactive({
      title: '',
      // address: '',
      status: '0',
      img: '',
      tinymceValue: '12'
    })
    // const visible = ref(false)
    const modalVisible = computed({
      get: () => props.visible,
      set: val => {
        emit('update:visible', val)
      }
    })
    const disabled = ref(false) //是否显示弹窗

    const contentCategory = [
      { name: '我的', id: 1 },
      { name: '我的1', id: 2 }
    ]
    const rules = {
      title: [
        { required: true, message: '请输入内容标题!', trigger: 'change' },
        { min: 0, max: 20, message: '文字超出限制范围!', trigger: 'blur' }
      ],
      address: [{ required: true, message: '请选择内容分类!', trigger: 'change' }],
      tinymceValue: [{ required: true, message: '请输入内容!', trigger: 'blur' }]
    }
    const handleChange = value => {
      console.log(`selected ${value}`)
    }
    const previewVisible = ref(false)
    const previewImage = ref('')
    const fileList = ref([
      {
        uid: '-2',
        status: 'done',
        url: 'https://img1.baidu.com/it/u=68692349,1752997792&fm=26&fmt=auto'
      }
    ])
    const loading = ref(false)
    const imageUrl = ref('')

    function getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    }
    const handleCancel = () => {
      previewVisible.value = false
    }

    const handlePreview = async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }

    const handleChange1 = info => {
      if (info.file.status === 'uploading') {
        loading.value = true
        return
      }

      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl.value = base64Url
          loading.value = false
        })
      }

      if (info.file.status === 'error') {
        loading.value = false
        message.error('上传错误')
      }
    }

    const beforeUpload = file => {
      const isJpgOrPng =
        file.type === 'image/psd' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpeg'

      if (!isJpgOrPng) {
        message.error('图片格式不正确!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isLt2M) {
        message.error('图片大小不超过5MB!')
      }
      return isJpgOrPng && isLt2M
    }

    const tinymceInput = value => {
      modalForm.tinymceValue = value
    }

    // 保存
    const save = () => {
      modalRef.value
        .validate()
        .then(() => {
          console.log(modalForm, '表单内容')
          message.success('成功提交')
          // 提交表单
          // 关闭弹窗
          // emit('closeModal')
        })
        .catch(error => {
          console.log('error', error)
        })
    }

    // 取消，右上角这个关闭也要调用这个方法
    const cancle = () => {
      emit('closeModal')
    }

    console.log(props.data, '接收的数据是')

    onMounted(() => {
      headerTitle.value = props.data.type == 1 ? '编辑内容' : props.data.type == 2 ? '查看内容' : '新增内容'

      disabled.value = props.data.type == 2 ? true : false
    })
    return {
      modalRef,
      modalForm,
      contentCategory,
      disabled,
      loading,
      imageUrl,
      labelCol: { span: 3 },
      wrapperCol: { span: 14 },
      headerTitle,
      previewVisible,
      previewImage,
      fileList,
      rules,
      tinymceInput,
      handleCancel,
      handlePreview,
      handleChange,
      handleChange1,
      beforeUpload,
      save,
      cancle,
      modalVisible
    }
  }
}
</script>
<style scoped lang="less"></style>
